package cn.xn.hrms.domain.service.impl;

import cn.xn.hrms.api.dto.res.RoleDTO;
import cn.xn.hrms.api.dto.res.UserDTO;
import cn.xn.hrms.infrastructure.dao.RoleDao;
import cn.xn.hrms.infrastructure.dao.RoleMenuDao;
import cn.xn.hrms.infrastructure.dao.UserRoleDao;
import cn.xn.hrms.api.dto.res.RoleMenuDTO;
import cn.xn.hrms.domain.service.RoleService;
import cn.xn.hrms.api.dto.req.RoleMenuReqDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author: ysz
 * @date: 2023/08/06
 **/
@Slf4j
@Component
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Resource
    private RoleMenuDao roleMenuDao;

    @Resource
    private UserRoleDao userRoleDao;


    @Override
    public void add(RoleDTO roleDTO) {
        roleDao.insertSelective(roleDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Integer> ids) {
        roleDao.updateIsDeletedByIdIn(1, ids);
        // 删除用户角色映射关系
        userRoleDao.updateIsDeletedByRoleIdIn(1, ids);
        // 删除角色菜单映射
        roleMenuDao.updateIsDeletedByRoleIdIn(1, ids);
    }

    @Override
    public List<RoleDTO> list() {
        return roleDao.selectAll();
    }

    @Override
    public void update(RoleDTO roleDTO) {
        roleDao.updateByPrimaryKeySelective(roleDTO);
    }

    @Override
    public PageInfo<RoleDTO> pageList(Integer page, Integer size, String name, String description) {
        PageHelper.startPage(page, size);
        List<RoleDTO> roleDTOList = roleDao.listPage(name, description);
        return new PageInfo<>(roleDTOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleMenus(RoleMenuReqDTO roleMenuReqDTO) {

        roleMenuDao.updateIsDeletedByRoleIdIn(1, Arrays.asList(Integer.valueOf(String.valueOf(roleMenuReqDTO.getRoleId()))));

        List<RoleMenuDTO> insertList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(roleMenuReqDTO.getMenuIds())) {
            for (Long menuId : roleMenuReqDTO.getMenuIds()) {
                RoleMenuDTO menuDTO = new RoleMenuDTO();
                menuDTO.setMenuId(menuId);
                menuDTO.setRoleId(roleMenuReqDTO.getRoleId());
                insertList.add(menuDTO);
            }
        }

        if (!CollectionUtils.isEmpty(insertList)) {
            roleMenuDao.insertList(insertList);
        }

    }

    @Override
    public List<RoleMenuDTO> getRoleMenuList(Long roleId) {

        return roleMenuDao.findAllByRoleIdIn(Arrays.asList(roleId));
    }
}
